<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="学科/专业名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入学科/专业名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门类" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入门类"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['DataManage:subject_tree:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="subject_treeList"
      :row-key="row => row.id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren', label: 'name'}"
    >

      <el-table-column label="学科/专业名称" prop="name" width="260"></el-table-column>
      <el-table-column label="类型" align="center" prop="type" width="230">
        <template slot-scope="scope">
          <span v-if="scope.row.type === 0">学科</span>
          <span v-else-if="scope.row.type === 1">专业</span>
        </template>
      </el-table-column>
      <el-table-column label="学校" align="center" prop="universityName"/>
      <el-table-column label="门类" align="center" prop="categoryName" width="200"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="280">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['DataManage:subject_tree:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['DataManage:subject_tree:add']"
          >新增
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['DataManage:subject_tree:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 添加或修改学科专业统计对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级目录" prop="parentId">
          <treeselect v-model="form.parentId" :options="subject_treeOptions" :normalizer="normalizer"
                      placeholder="请选择上级目录"/>
        </el-form-item>
        <el-form-item label="学科/专业名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入学科/专业名称"/>
        </el-form-item>
        <el-form-item label="学校" prop="universityId">
          <el-select v-model="form.universityId"
                     @change="getUniversityPromotion(form.universityId)"
                     style="width: 80%"
                     placeholder="请选择"
                     :disabled="form.universityId === '无数据'">
            <el-option v-for="item in universityList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="门类" prop="categoryId">
          <el-select v-model="form.categoryId"
                     style="width: 80%"
                     placeholder="请先选择学校，再选择门类"
                     :disabled="form.categoryId === '无数据'"
                     @change="changeGame(form.categoryId)">
            <el-option v-for="item in categoryList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSubject_tree, getSubject_tree, delSubject_tree,
  addSubject_tree, updateSubject_tree, universityList, categoryList
}
  from "@/api/DataManage/subject_tree";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Subject_tree",
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 学科专业统计表格数据
      subject_treeList: [],
      // 学科专业统计树选项
      subject_treeOptions: [],
      //学校Id
      universityId: '',
      //学校列表
      universityList: [],
      //门类Id
      categoryId: '',
      //门类列表
      categoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        name: null,
        categoryName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          {required: true, message: "id", trigger: "blur"}
        ],
        name: [
          {required: true, message: "名称不能为空", trigger: "blur"}
        ],
        type: [
          {required: true, message: "类型不能为空", trigger: "change"}
        ],
      }
    };
  },
  mounted() {
    this.getUniversityList();
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询学科专业统计列表 */
    getList() {
      this.loading = true;
      listSubject_tree(this.queryParams).then(response => {
        this.subject_treeList = this.handleTree(response.data, "id", "parentId");
        this.loading = false;
      });
    },
    /** 转换学科专业统计数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查询学科专业统计下拉树结构 */
    getTreeselect() {
      listSubject_tree().then(response => {
        this.subject_treeOptions = [];
        const data = {id: 0, name: '顶级节点', children: []};
        data.children = this.handleTree(response.data, "id", "parentId");
        this.subject_treeOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        name: null,
        type: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加学科专业统计";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const id = row.id || this.ids
      getSubject_tree(id).then(response => {
        this.form = response.data;
        // 如果是通识课程，则不进行学校和专业的回显
        this.open = true;
        // 根据学校 ID 获取专业列表，并匹配专业名称
        this.checkUniversityPromotion(this.form.universityId);
        this.title = "修改学科/专业信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 根据parentId的值来动态设置type的值
          if (this.form.parentId === 0) {
            this.form.type = 0; // parentId为0时，type设置为0
          } else {
            this.form.type = 1; // 其他情况下，type设置为1
          }
          if (this.form.id != null) {
            updateSubject_tree(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSubject_tree(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除学科专业统计编号为"' + row.id + '"的数据项？').then(function () {
        return delSubject_tree(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    //获取学校下拉数据
    getUniversityList() {
      this.loading = true;
      universityList()
        .then(res => {
          this.universityList = res.data.map(item => {
            return {value: item.id, label: item.name};
          });
        }).catch(() => {
        // 处理错误
      });
    },
    //获取专业下拉数据
    checkUniversityPromotion(universityId) {
      this.open = false; // 隐藏修改弹窗

      if(universityId != null){
        categoryList(universityId)
          .then(res => {
            this.categoryList = res.data.map(item => {
              return {value: item.id, label: item.name};
            });
            // 匹配专业名称
            const selectedCategory = this.categoryList.find(category => category.value === this.form.categoryId);
            if (selectedCategory) {
              this.form.categoryName = selectedCategory.label;
            }

          })
          .catch(() => {
            // 处理错误
          });
      }
      else{
        this.form.universityId = '无数据';
        this.form.categoryId = '无数据';
      }
      this.open = true; // 显示修改弹窗
    },

    getUniversityPromotion(universityId) {

      // 清空当前选中的专业ID
      this.form.categoryId = null;
      // 清空专业列表
      this.categoryList = [];
      // 重置专业名称字段
      this.form.categoryName = '';

      categoryList(universityId).then(res => {
        this.categoryList = res.data.map(item => {
          return {value: item.id, label: item.name};
        });
        // 匹配专业名称

        const selectedCategory = this.categoryList.find(category => category.value === this.form.categoryId);
        if (selectedCategory) {
          this.form.categoryId = selectedCategory.value;
          this.form.categoryName = selectedCategory.label;
        }
      })
        .catch(() => {
          // 处理错误
        });
    },
    changeGame(id){
      this.$forceUpdate() //在下拉框上绑定change事件 更新视图 这样就不会有视图更新的问题
    },

  }
};
</script>
